package movies
{
	import flash.filesystem.File;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import org.osflash.signals.Signal;
	/**
	 * Check file or folder to find movies
	 */
	public class FolderBrowser
	{
		protected var _urlFound:Signal;
		protected var _urls:Array;
		protected var _extensions:Array;
		protected var _urlRemaining:Array;
		protected var settimeout:uint;
		public function FolderBrowser(urls:Array = null, extensions:Array = null)
		{
			if(urls == null)
			{
				urls = new Array();
			}
			if(extensions == null)
			{
				extensions = new Array();
			}
			_urlFound = new Signal(String);
			_extensions = extensions;
			this.urls = urls;
		}
		public function get urlFound():Signal
		{
			return _urlFound;
		}
		public function get urls():Array
		{
			return _urls;
		}
		public function set urls(value:Array):void
		{
			_urls = value;
			reset();
		}
		public function get extensions():Array
		{
			return _extensions;
		}
		public function set extensions(value:Array):void
		{
			_extensions = value;
			reset();			
		}
		protected function next():void
		{
			if(_urlRemaining.length>0)
			{
				get(_urlRemaining.shift());
			}
		}
		protected function reset():void
		{
			stop();
			_urlRemaining = new Array();
			_urlRemaining = _urls.concat(new Array());
			next();
		}
		protected function stop():void
		{
			flash.utils.clearTimeout(settimeout);
		}
		protected function get(url:String):void
		{
			try
			{
				var file:File = new File(url);
				var i:int;
				var files:Array;
				if(file.exists)
				{
					if(!file.isDirectory)
					{
						
					  files = LocalFile.read(url).split("\n");
					  for(i = 0; i<files.length; i++)
					  {
					  	_urlRemaining.push(files[i]);
					  }
					}else
					{
						files = file.getDirectoryListing();
						for(i = 0; i<files.length; i++)
						{
							if((files[i] as File).isDirectory)
							{
								_urlRemaining.push((files[i] as File).nativePath);
							}else
							{
								if(extensions.indexOf((files[i] as File).extension.toLowerCase())>-1)
								{
									_urlFound.dispatch((files[i] as File).nativePath);
								} 
							}
						}
					}
				}
			}
			catch(e:Error)
			{
				//trace("Error ["+url+"] : "+e.toString());
			}
			settimeout = flash.utils.setTimeout(next,100);
		}
	}
}